#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WebDAV管理工具
提供命令行界面来管理账号和用户
"""

import os
import sys
import argparse
from typing import List

# 添加项目根目录到路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

from src.common.database import init_global_session
from .account_manager import account_manager
from src.utils.config import get_db_config

def init_system():
    """初始化系统"""
    try:
        init_global_session()
        print("系统初始化成功")
    except Exception as e:
        print(f"系统初始化失败: {e}")
        sys.exit(1)

def list_cloud_accounts():
    """列出云盘账号"""
    accounts = account_manager.list_cloud_accounts(active_only=False)
    
    if not accounts:
        print("没有找到云盘账号")
        return
    
    print("云盘账号列表:")
    print("-" * 80)
    print(f"{'ID':<5} {'账号':<20} {'显示名称':<20} {'状态':<8} {'创建时间':<20}")
    print("-" * 80)
    
    for account in accounts:
        status = "激活" if account['is_active'] else "禁用"
        print(f"{account['id']:<5} {account['cloud_account']:<20} {account['display_name']:<20} {status:<8} {account['created_at'].strftime('%Y-%m-%d %H:%M'):<20}")

def add_cloud_account(cloud_account: str, cloud_password: str, display_name: str = None):
    """添加云盘账号"""
    account = account_manager.add_cloud_account(
        cloud_account=cloud_account,
        cloud_password=cloud_password,
        display_name=display_name
    )
    
    if account:
        print(f"添加云盘账号成功: {cloud_account} (ID: {account.id})")
        
        # 测试连接
        print("正在测试账号连接...")
        result = account_manager.test_cloud_account(account.id)
        if result['success']:
            print(f"✓ {result['message']}")
        else:
            print(f"✗ {result['error']}")
    else:
        print(f"添加云盘账号失败: {cloud_account}")

def remove_cloud_account(account_id: int):
    """删除云盘账号"""
    account = account_manager.get_cloud_account(account_id)
    if not account:
        print(f"账号不存在: {account_id}")
        return
    
    confirm = input(f"确认删除账号 '{account.cloud_account}' (ID: {account_id})? [y/N]: ")
    if confirm.lower() != 'y':
        print("取消删除")
        return
    
    if account_manager.remove_cloud_account(account_id):
        print(f"删除云盘账号成功: {account.cloud_account}")
    else:
        print(f"删除云盘账号失败: {account.cloud_account}")

def test_cloud_account(account_id: int):
    """测试云盘账号"""
    result = account_manager.test_cloud_account(account_id)
    
    if result['success']:
        print(f"✓ 账号连接正常: {result['message']}")
    else:
        print(f"✗ 账号连接失败: {result['error']}")

def show_account_stats(account_id: int):
    """显示账号统计信息"""
    stats = account_manager.get_account_stats(account_id)
    
    if not stats:
        print(f"账号不存在: {account_id}")
        return
    
    print(f"账号统计信息:")
    print(f"  账号ID: {stats['account_id']}")
    print(f"  云盘账号: {stats['cloud_account']}")
    print(f"  显示名称: {stats['display_name']}")
    print(f"  状态: {'激活' if stats['is_active'] else '禁用'}")
    print(f"  文件数量: {stats['file_count']}")
    print(f"  总大小: {stats['total_size'] / 1024 / 1024:.2f} MB")
    print(f"  创建时间: {stats['created_at']}")
    print(f"  更新时间: {stats['updated_at']}")

def list_webdav_users():
    """列出WebDAV用户"""
    users = account_manager.list_webdav_users(active_only=False)
    
    if not users:
        print("没有找到WebDAV用户")
        return
    
    print("WebDAV用户列表:")
    print("-" * 80)
    print(f"{'ID':<5} {'用户名':<15} {'根路径':<20} {'权限':<15} {'状态':<8} {'创建时间':<20}")
    print("-" * 80)
    
    for user in users:
        permissions = []
        if user['can_read']:
            permissions.append('读')
        if user['can_write']:
            permissions.append('写')
        if user['can_delete']:
            permissions.append('删')
        
        perm_str = ','.join(permissions) if permissions else '无'
        status = "激活" if user['is_active'] else "禁用"
        root_path = user['root_path'] if user['root_path'] is not None else '/'
        
        created_time = user['created_at'].strftime('%Y-%m-%d %H:%M') if user['created_at'] else '未知'
        print(f"{user['id']:<5} {user['username']:<15} {root_path:<20} {perm_str:<15} {status:<8} {created_time:<20}")

def add_webdav_user(username: str, password: str, root_path: str = '/'):
    """添加WebDAV用户"""
    user = account_manager.add_webdav_user(
        username=username,
        password=password,
        root_path=root_path
    )
    
    if user:
        print(f"添加WebDAV用户成功: {username} (ID: {user.id})")
    else:
        print(f"添加WebDAV用户失败: {username}")

def remove_webdav_user(user_id: int):
    """删除WebDAV用户"""
    users = account_manager.list_webdav_users(active_only=False)
    user = next((u for u in users if u.id == user_id), None)
    
    if not user:
        print(f"用户不存在: {user_id}")
        return
    
    confirm = input(f"确认删除用户 '{user.username}' (ID: {user_id})? [y/N]: ")
    if confirm.lower() != 'y':
        print("取消删除")
        return
    
    if account_manager.remove_webdav_user(user_id):
        print(f"删除WebDAV用户成功: {user.username}")
    else:
        print(f"删除WebDAV用户失败: {user.username}")

def change_user_password(user_id: int, new_password: str):
    """修改用户密码"""
    if account_manager.update_webdav_user_password(user_id, new_password):
        print(f"修改用户密码成功: {user_id}")
    else:
        print(f"修改用户密码失败: {user_id}")

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='WebDAV管理工具')
    subparsers = parser.add_subparsers(dest='command', help='可用命令')
    
    # 初始化命令
    subparsers.add_parser('init', help='初始化系统')
    
    # 云盘账号管理
    account_parser = subparsers.add_parser('account', help='云盘账号管理')
    account_subparsers = account_parser.add_subparsers(dest='account_action')
    
    account_subparsers.add_parser('list', help='列出云盘账号')
    
    add_account_parser = account_subparsers.add_parser('add', help='添加云盘账号')
    add_account_parser.add_argument('cloud_account', help='云盘账号')
    add_account_parser.add_argument('cloud_password', help='云盘密码')
    add_account_parser.add_argument('--display-name', help='显示名称')
    
    remove_account_parser = account_subparsers.add_parser('remove', help='删除云盘账号')
    remove_account_parser.add_argument('account_id', type=int, help='账号ID')
    
    test_account_parser = account_subparsers.add_parser('test', help='测试云盘账号')
    test_account_parser.add_argument('account_id', type=int, help='账号ID')
    
    stats_account_parser = account_subparsers.add_parser('stats', help='显示账号统计')
    stats_account_parser.add_argument('account_id', type=int, help='账号ID')
    
    # WebDAV用户管理
    user_parser = subparsers.add_parser('user', help='WebDAV用户管理')
    user_subparsers = user_parser.add_subparsers(dest='user_action')
    
    user_subparsers.add_parser('list', help='列出WebDAV用户')
    
    add_user_parser = user_subparsers.add_parser('add', help='添加WebDAV用户')
    add_user_parser.add_argument('username', help='用户名')
    add_user_parser.add_argument('password', help='密码')
    add_user_parser.add_argument('--root-path', default='/', help='根路径')
    
    remove_user_parser = user_subparsers.add_parser('remove', help='删除WebDAV用户')
    remove_user_parser.add_argument('user_id', type=int, help='用户ID')
    
    passwd_user_parser = user_subparsers.add_parser('passwd', help='修改用户密码')
    passwd_user_parser.add_argument('user_id', type=int, help='用户ID')
    passwd_user_parser.add_argument('new_password', help='新密码')
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return
    
    if args.command == 'init':
        init_system()
    elif args.command == 'account':
        if not args.account_action:
            account_parser.print_help()
            return
        
        init_system()
        
        if args.account_action == 'list':
            list_cloud_accounts()
        elif args.account_action == 'add':
            add_cloud_account(args.cloud_account, args.cloud_password, args.display_name)
        elif args.account_action == 'remove':
            remove_cloud_account(args.account_id)
        elif args.account_action == 'test':
            test_cloud_account(args.account_id)
        elif args.account_action == 'stats':
            show_account_stats(args.account_id)
    
    elif args.command == 'user':
        if not args.user_action:
            user_parser.print_help()
            return
        
        init_system()
        
        if args.user_action == 'list':
            list_webdav_users()
        elif args.user_action == 'add':
            add_webdav_user(args.username, args.password, args.root_path)
        elif args.user_action == 'remove':
            remove_webdav_user(args.user_id)
        elif args.user_action == 'passwd':
            change_user_password(args.user_id, args.new_password)

if __name__ == '__main__':
    main()